package com.nus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import com.nus.database.DBAdaptor;
import com.nus.datafeeder.Companies_Data;

import android.R.integer;
import android.R.string;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CareerCenterDetails extends Activity {
	private static final int HELLO_ID = 0;
	private Context context;
	public ImageButton home;
  public String time1;
  public String date1;
  public String name;
  public String value;
  protected TextView title;
  private static final int REQUEST_CODE = 1234;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.careercenterdetails);
		 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
		 title = (TextView) findViewById(R.id.titleheader);
		 title.setText("Career Center");
		/*home = (ImageButton) findViewById(R.id.home);
		home.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.nus.OptionsActivity"));
			}
		});*/
		 ImageView b = (ImageView)findViewById(R.id.home);
		  b.setImageDrawable(getResources().getDrawable(R.drawable.careercenter));
		boolean netconn = checkInternetConnection();
		if (!netconn) {
			Toast.makeText(getApplicationContext(),
					"Please check your internet or 3G connection",
					Toast.LENGTH_LONG).show();
		}
		TextView name_tv = (TextView) findViewById(R.id.name);

		Bundle bundle = getIntent().getExtras();
		name_tv.setText(bundle.getString("NAME"));
		name = bundle.getString("NAME");
		TextView desc_tv = (TextView) findViewById(R.id.desc);
		desc_tv.setText(bundle.getString("DESC"));
		this.date1=bundle.getString("DESC");
		TextView time_tv = (TextView) findViewById(R.id.time);
		time_tv.setText(bundle.getString("TIME"));
		this.time1 = bundle.getString("TIME");
		TextView ddtext_tv = (TextView) findViewById(R.id.det_text);
		ddtext_tv.setText(bundle.getString("DTEXT"));
		Button button = (Button) findViewById(R.id.addRem);

		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startVoiceRecognitionActivity();
			}
		});

	}

	 /**
     * Handle the action of the button being clicked
     */
    public void speakButtonClicked(View v)
    {
        startVoiceRecognitionActivity();
    }
 
    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity()
    {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "NdroidUS Reminder");
        startActivityForResult(intent, REQUEST_CODE);
    }
 
    /**
     * Handle the results from the voice recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
        {
            // Populate the wordsList with the String values the recognition engine thought it heard
           final ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Did you mean this  "+"\""+matches.get(0)+"\"")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
//                     MyActivity.this.finish();
                	Matcher m=null;
                	Pattern p = Pattern.compile("[0-9]+");
                	StringTokenizer st= new StringTokenizer(matches.get(0), " ");
                	while(st.hasMoreTokens()){
                		String token=st.nextToken();
                		Log.i("voice","value of token"+token);
                		m = p.matcher(token);
                		boolean result=m.find();
                		Log.i("voice"," value of m.find"+result);
                	
//                	Matcher m = p.matcher(matches.get(0));

                	if (result) {
//                	    System.out.println(m.group(1));
                		value=token;
                		int day = Integer.parseInt(date1.substring(0, 2));
      				  int month = Integer.parseInt(date1.substring(3, 5));
      				  int year = Integer.parseInt(date1.substring(6, 10));
      				  int hour = Integer.parseInt(time1.substring(0, 2));
      				  int mins = Integer.parseInt(value)*-1;
      				  setReminder(mins, hour, day, month-1, year, "", name);
                	  //  Toast.makeText(CareerCenterDetails.this, token, Toast.LENGTH_SHORT).show();
                	}
                	}
                }
            })
            .setNegativeButton("Try Again", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                	dialog.cancel();
                	startVoiceRecognitionActivity();
//                     dialog.cancel();
                }
            }
            )
            .setNeutralButton("Keyboard",  new DialogInterface.OnClickListener() {
				
//				String mins;
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					AlertDialog.Builder alert = new AlertDialog.Builder(CareerCenterDetails.this);

					alert.setTitle("NUS Reminder");
					alert.setMessage("When do you want to be reminded?");

					// Set an EditText view to get user input
					final EditText inputName = new EditText(CareerCenterDetails.this);
					alert.setView(inputName);

					alert.setPositiveButton("Set Time", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					value = inputName.getText().toString();
					
            		int day = Integer.parseInt(date1.substring(0, 2));
  				  int month = Integer.parseInt(date1.substring(3, 5));
  				  int year = Integer.parseInt(date1.substring(6, 10));
  				  int hour = Integer.parseInt(time1.substring(0, 2));
  				  int mins = Integer.parseInt(value)*-1;
  				  setReminder(mins, hour, day, month-1, year, "", name);
					}
					});

					alert.show();

					
					
				}
			});
     AlertDialog alert = builder.create();
     alert.show();
//            wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
//                    matches));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
	public  void setReminder(int mins,int hours,int day,int month,int year,String location,String reminderdesc){
		  Calendar cal = Calendar.getInstance();
		  DBAdaptor db = new DBAdaptor(this);
		    cal.set(Calendar.MONTH, month);
			cal.set(Calendar.YEAR, year);				
			cal.set(Calendar.DAY_OF_MONTH, day);
			cal.set(Calendar.HOUR_OF_DAY, hours);
			cal.set(Calendar.MINUTE, 00);
			Intent alarmintent = new Intent(this, AlarmReceiver.class);
			String title = cal.getTime().toLocaleString();
			alarmintent.putExtra("title",title);
			alarmintent.putExtra("note",reminderdesc);
			cal.add(Calendar.MINUTE, mins);
			//HELLO_ID is a static variable that must be initialised at the BEGINNING OF CLASS with 1;
			Date d = cal.getTime();
			db.open();
			long id = db.insertRemainder(title,reminderdesc,d.getTime());
			Log.i(" data insertion"," return value are inserting is"+id);
			 db.close();

			//example:protected static int HELLO_ID =1;
			PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID,
			alarmintent,PendingIntent.FLAG_UPDATE_CURRENT|  Intent.FILL_IN_DATA);
			//VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send correct extra's informations to 
			//AlarmReceiver Class
					// Get the AlarmManager service

			AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
			am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
		    String toasttext = "Reminder set for:"+title;
		    addTocal(cal,title+":"+  reminderdesc);
			Toast toast = Toast.makeText(CareerCenterDetails.this, toasttext, Toast.LENGTH_LONG);
			toast.show();
			
			
	  }
	public boolean checkInternetConnection() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		if (cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isAvailable()
				&& cm.getActiveNetworkInfo().isConnected()) {
			return true;

		} else {
			return false;
		}
	}
	public void addTocal(Calendar cal1,String desc){

		String[] projection = new String[] { "_id", "name" };
		Uri calendars = Uri.parse("content://com.android.calendar/calendars");
		     
		String calName; 
		 String calId = null; 
		Cursor managedCursor =
		   managedQuery(calendars, projection,
		   "selected=1", null, null);
		if (managedCursor.moveToFirst()) {
			 
			 int nameColumn = managedCursor.getColumnIndex("name"); 
			 int idColumn = managedCursor.getColumnIndex("_id");
			 do {
			    calName = managedCursor.getString(nameColumn);
			    calId = managedCursor.getString(idColumn);
			 } while (managedCursor.moveToNext());
			}
		
		
		ContentValues event = new ContentValues();
		
		event.put("calendar_id", calId);
		event.put("title", "NUS Career Center");
		event.put("description", desc);
		//event.put("eventLocation", "Event Location");
		long startTime = cal1.getTimeInMillis();
		long endTime = cal1.getTimeInMillis()+60*60*1000;
		event.put("dtstart", startTime);
		event.put("dtend", endTime);
		event.put("allDay", 1); 
		event.put("eventStatus", 1);
		event.put("visibility", 0);
	//	event.put("hasAlarm", 1);
		Uri eventsUri = Uri.parse("content://com.android.calendar/events");
		  Uri url = getContentResolver().insert(eventsUri, event);
		
	}
}
